<template>
  <div>
    <Row :gutter="4" >
<!--      <Col span="3"><Dateselect ref="eventTime" v-model="dateRange" :placeholder="param.date"></Dateselect> </Col>-->
      <Col span="4"><DateTimeRangeSelect ref="eventTime" v-model="dateRange" :placeholder="$t('datetime')" width="100%"></DateTimeRangeSelect></Col>
      <Col span="4">
<!--        <Input clearable :placeholder="param.deviceCode" v-model="queryParam.where.deviceCode"></Input>-->
        <Device5gModelSelect :cate=2 ref="Device5gModelSelect" width="100px" v-model="queryParam.where.deviceId"></Device5gModelSelect>
      </Col>
      <Col span="4"><OrganizationTree ref="srhOrgSelect" width="200px" v-model="queryParam.where.orgId" :placeholder="param.organization"></OrganizationTree> </Col>
      <Col span="4"><UserSelect ref="srhUserSelect" width="200px" v-model="queryParam.where.userId" :placeholder="param.user"></UserSelect> </Col>
      <Col span="1"><Button type="primary" icon="ios-search" @click="getData">{{param.search}}</Button></Col>
    </Row>

    <Table border :columns="columns" :data="tableData" :loading="tableLoading">
      <template slot-scope="{ row, index }" slot="map">
        <Button :disabled="!(!!row.position)" type="default" :Title="$t('map')" icon="md-globe" style="margin-right: 3px" @click="openMap(row)"></Button>
      </template>
    </Table>
    <TopnavPage v-model="queryParam.page" @changePage="changePage"></TopnavPage>

    <Modal v-model="map.show" :title="map.title" width="730px">
      <Row>
        <Col span="4">
          <Button icon="md-arrow-back" :title="$t('back')" @click="back"></Button>
          <Button icon="md-arrow-forward" :title="$t('next')" style="margin-left: 10px" @click="next"></Button>
        </Col>
        <Col span="6">
          <span>{{curRow.time}}</span>
        </Col>
        <Col span="14">
          <span>{{curRow.position}}</span>
        </Col>
      </Row>
<!--      <Row>
        <Col span="4"></Col>
        <Col span="9">
          <span>{{curRow.time}}</span>
        </Col>
        <Col span="9">
          <span>{{curRow.position}}</span>
        </Col>
      </Row>-->
      <div id="locateMap" ref="locateMap" style="height:500px;width:700px;background-color: #FFFFFF"></div>
    </Modal>
  </div>
</template>
<script>
import DateTimeRangeSelect from "_c/topnav/DateTimeRangeSelect"
import TopnavPage from "_c/topnav/TopnavPage";
import OrganizationTree from "_c/topnav/OrganizationTree";
import Dateselect from "_c/topnav/date2select"
import UserSelect from "_c/topnav/UserModelSelect";
import DevicePosition from '@/api/DevicePosition.js'
import {apiResult} from "@/libs/util";
import Device5gModelSelect from "_c/topnav/Device5gModelSelect";
import MapInfo from "@/view/Home/map/maptools/data/MapInfo";
import LayerVector from "ol/layer/Vector";
import SourceVector from "ol/source/Vector";
import {pointStyle, polygonStyle} from "@/view/Home/map/maptools/tool/style";
import {solveGps} from "@/view/Home/map/maptools/tool/GpsUtils";
import {Map, View} from "ol";
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import Feature from "ol/Feature";
import Point from "ol/geom/Point";
export default {
  name:"LocationDetail",
  components:{TopnavPage,Device5gModelSelect,DateTimeRangeSelect,OrganizationTree,UserSelect},
  computed: {

    columns() {
      return [
        {title: this.$t('device_code'), key: 'deviceCode', sortable: true,width: 200,align: 'center',ellipsis:true,tooltip:true,tooltipTheme:'light'},
        {title: this.$t('device_name'), key: 'deviceName', sortable: true, width: 200,ellipsis:true,tooltip:true,tooltipTheme:'light'},
        {title: this.$t('report_time'), key: 'time', sortable: true, width: 200,ellipsis:true,tooltip:true,tooltipTheme:'light'},
        {title: this.$t('longitude'), key: 'longitude', sortable: true, ellipsis:true,width: 200},
        {title: this.$t('latitude'), key: 'latitude', sortable: true,ellipsis:true,width: 200,align: 'center'},
        {title: this.$t('coordinate_system'), key: 'coordinateSystem', sortable: true, width: 200},
        {title: '', key: '', sortable: true, width: 80,slot:"map"},
      ]
    }
  },
  data() {
    return {
      api: new DevicePosition(),
      dateRange: [],
      param:{
          date: this.$t('date'),
          deviceCode: this.$t('device_code'),
          alarmType: this.$t('alarm_type'),
          search: this.$t('search'),
          organization: this.$t('select_organization'),
          user: this.$t('select_people')
      },
      queryParam: {
        page: {
          pages: 1,
          size: 15,
          total: 0,
          current: 1,
          orders:[
            {column:'p.id',asc:false}
          ]
        },
        where: {
          keyword: null,
          deviceId: null,
          beginTime: null,
          endTime: null,
          userId: null,
          orgId: null,
          deviceCode: null,
          isGroupBy: false,
        },
      },
      tableData: [],
      tableLoading: false,
      map:{
        title: "",
        show:false,
        obj:null,
        mapInfo:null,
        customLayers:{
          layerVector: null,
          sourceVector: null,
        },
      },
      curRow:{
        deviceName:"3232",
        time:"time",
        position:"position",
        coordinateSystem: "WGS84",
        curIndex: 0,
        maxIndex: 0
      },
      point: null, //地图上的点
    }

  },
  methods:{
    back(){
      //上一条
      this.curRow.curIndex--;
      if (this.curRow.curIndex < 0){
        this.curRow.curIndex = 0;
      }else{
        this.moveRecordInMap();
      }
    },
    next(){
      //下一条
      this.curRow.curIndex++;
      if (this.curRow.curIndex >= this.tableData.length){
        this.curRow.curIndex--;
      }else{
        this.moveRecordInMap();
      }
    },

    moveRecordInMap(){
      const i = this.curRow.curIndex;
      this.curRow.deviceName = this.tableData[i].deviceName;
      this.curRow.time = this.tableData[i].time;
      this.curRow.position = this.tableData[i].position;
      this.curRow.coordinateSystem = this.tableData[i].coordinateSystem;

      if (!!this.point){
        this.map.customLayers.sourceVector.removeFeature(this.point);
      }
      const pos1 =  this.curRow.position.split(",");
      let pos = [];
      pos.push(parseFloat(pos1[0]));
      pos.push(parseFloat(pos1[1]));
      //坐标系转换
      const gpsData = solveGps(this.curRow.coordinateSystem,pos[1],pos[0]);
      if (!!gpsData){
        pos[0]=gpsData.lon;
        pos[1]=gpsData.lat;
      }
      this.point = new Feature({
        geometry: new Point(pos),
      });
      this.point.setStyle(pointStyle({online:"1",title:this.curRow.deviceName}));
      this.map.customLayers.sourceVector.addFeature(this.point);
      //移到这个中心点上
      this.map.mapObj.getView().setCenter(pos);

    },
    openMap(row){
      this.map.show = true;
      if (this.map.show) {
        this.$nextTick(() => {
          this.initMap(row);
        })
      }
    },
    initMap(row){
      this.curRow.deviceName = row.deviceName;
      this.curRow.time = row.time;
      this.curRow.position = row.position;
      this.curRow.coordinateSystem = row.coordinateSystem;

      //定位表格数据某个点
      if (!!this.tableData && this.tableData.length > 0){
        for(let i=0;i<this.tableData.length;i++){
          if (row.id === this.tableData[i].id){
            this.curRow.curIndex = i;
            break;
          }
        }
      }

      if (!!this.map.mapObj){
        this.map.mapObj.setTarget(null);
        this.map.mapObj.dispose()
        this.map.mapObj = null;
        this.map.customLayers.layerVector = null;
        this.map.customLayers.sourceVector = null;
      }
      this.map.mapInfo = new MapInfo().get();
      this.map.customLayers.layerVector =  new LayerVector();
      this.map.customLayers.sourceVector =  new SourceVector();
      this.map.customLayers.layerVector.setSource(this.map.customLayers.sourceVector);
      this.map.customLayers.layerVector.setStyle(polygonStyle);
      const that = this;
      const pos1 =  this.curRow.position.split(",");
      let pos = [];
      pos.push(parseFloat(pos1[0]));
      pos.push(parseFloat(pos1[1]));
      //坐标系转换
      const gpsData = solveGps(this.curRow.coordinateSystem,pos[1],pos[0]);
      if (!!gpsData){
        pos[0]=gpsData.lon;
        pos[1]=gpsData.lat;
      }
      that.map.mapObj = new Map({
        target: "locateMap", // 指向对象
        layers: [
          new TileLayer({
            source: new XYZ({
              url: that.map.mapInfo.sub.url[0]
            }),
          })
        ],
        loadTilesWhileAnimating: true,//支持动画
        view: new View({
          projection: this.map.mapInfo.projection, //"EPSG:4326",
          center: pos,
          zoom: 16,
        })
      });

      that.map.mapObj.addLayer(that.map.customLayers.layerVector);

      this.point = new Feature({
        geometry: new Point(pos),
      });
      this.point.setStyle(pointStyle({online:"1",title:this.curRow.deviceName}));
      this.map.customLayers.sourceVector.addFeature(this.point);
    },
    changePage() {
      this.getData()
    },
    getData() {
      /** 生成查询条件 */
      if (!(this.dateRange == null || this.dateRange.length < 2 || !this.dateRange[0])) {
        this.queryParam.where.beginTime = this.dateRange[0];
        this.queryParam.where.endTime = this.dateRange[1];
      }else{
        this.$Message.error(this.$t('param_time_empty'));
      }
      this.tableLoading = true;
      this.api.QueryByPage(JSON.stringify(this.queryParam)).then(res => {
        //console.log(res);
        this.tableData = [];
        apiResult(res.data,false,result=>{
          //console.log(result);
          this.queryParam.page.total = result.data.total;
          this.tableData = result.data.records;
          if (!!this.tableData && this.tableData.length > 0){
            this.tableData.forEach(item=>{
              if (!!item.longitude && !!item.latitude){
                item['position'] = item.longitude + ','+item.latitude
              }
            })
          }
          this.curRow.curIndex = 0;
        })
        this.tableLoading = false;
      }).catch(err=>{
        this.tableLoading = false;
      })
    }
  },
  mounted() {
    /** 为了显示用，调置默认值 */
    const end = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 2);
    start.setHours(0);
    start.setMinutes(0);
    start.setSeconds(0);
    start.setMilliseconds(0);
    end.setHours(23);
    end.setMinutes(59);
    end.setSeconds(59);
    end.setMilliseconds(999);
    this.dateRange = [start, end];
    this.getData();
  }
}
</script>
